package com.shulidata.mock.service;

import com.shulidata.mock.model.MockConf;
import com.shulidata.mock.repositories.MockConfRepository;
import com.shulidata.mock.service.groovy.GroovyUtils;
import com.shulidata.mock.utils.GenericException;
import com.shulidata.mock.utils.ServiceCode;
import com.shulidata.mock.utils.UniqueIdUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author fyduan
 * @date 16/4/29
 */
@Service
public class MockConfService {
    private static final Logger logger = LogManager.getLogger(MockConfService.class.getName());

    @Autowired
    MockConfRepository confRepository;

    // 新增或编辑一个mock配置
    @Transactional(rollbackFor = {RuntimeException.class, GenericException.class})
    public MockConf saveOrUpdate(MockConf conf) throws GenericException {
        // 执行方法将空格去掉
        conf.setScriptMethod(Strings.trimToNull(conf.getScriptMethod()));
        // 数据校验
        if (Strings.isBlank(conf.getServer()) || Strings.isBlank(conf.getApi())
                || Strings.isBlank(conf.getScript()) || Strings.isBlank(conf.getScriptMethod())) {
            throw new GenericException(ServiceCode.ERR_PARAM);
        }

        if (GroovyUtils.parseScript(conf.getScript()) == null) {
            throw new GenericException(ServiceCode.ERR_PARAM, "脚本内容错误");
        }

        boolean isNew = StringUtils.isEmpty(conf.getId());

        // 检查是否已经存在相同的配置
        MockConf _conf = confRepository.findByServerAndApi(conf.getServer(), conf.getApi());
        if (_conf != null && (isNew || !conf.getId().equals(_conf.getId()))) {
            throw new GenericException(ServiceCode.ERR_PARAM, "已经存在相同的服务接口配置");
        }

        conf.setModifyTime(System.currentTimeMillis());
        if (isNew) {
            conf.setId(UniqueIdUtils.compressUuid());
            confRepository.save(conf);
        } else {
            confRepository.update(conf);
        }

        return conf;
    }

    public MockConf findById(String id) {
        if (Strings.isBlank(id)) return null;
        return confRepository.get(id);
    }

    public List<MockConf> loadAll() {
        List<MockConf> list = confRepository.loadAll();
        if (list == null) list = new ArrayList<>();
        return list;
    }

    // 查找最近更新的脚本,间隔时间
    public List<MockConf> findLastUpdateByInterval(long intervals) {
        List<MockConf> list = confRepository.findAfterByTime(System.currentTimeMillis() - intervals);
        if (list == null) list = new ArrayList<>();
        return list;
    }

    public void deleteById(String id) {
        confRepository.delete(id);
    }
}
